import socket
import struct

# 定义服务器的IP和端口
host = '127.0.0.1'
port = 6666

# 定义变量来存储数据，初始值全部为0.0，为0.0时为无效值，对于没使用到的值应全部置0.0
get_check1 = 0.0       # 校验位1（888.0有效）
get_speed = 0.0       # 速度
get_mode = 0.0        # 飞行模式/任务：1.0表示...2.0表示...
get_doit = 0.0        # 执行确认位(1.0表示有效，0.0表示无效)
get_longitude = [0.0,0.0,0.0,0.0]   # 新建一个列表来存储经度,longitude[0]和latitude[0]为一对
get_latitude =  [0.0,0.0,0.0,0.0]   # 列表存储纬度
get_altitude =  [0.0,0.0,0.0,0.0]   # 列表存储海拔（高度）
get_check2 = 0.0       # 校验位（666.0有效）

send_check1 = 888.0
send_speed = 0.0
send_mode = 0.0        # 飞行模式/任务：1.0表示...2.0表示...
send_doit = 1.0        # 执行确认位(1.0表示有效，0.0表示无效)
send_longitude = [0.0,0.0,0.0,0.0]   # 新建一个列表来存储经度,longitude[0]和latitude[0]为一对
send_latitude =  [0.0,0.0,0.0,0.0]   # 列表存储纬度
send_altitude =  [0.0,0.0,0.0,0.0]   # 列表存储海拔（高度）
send_check2 = 666.0



# 创建 TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def start_server():
    # 绑定 IP 和端口
    server_socket.bind((host, port))
    
    # 开始监听连接
    server_socket.listen(5)  # 最多允许5个待连接的客户端
    print(f"服务器启动，监听 {host}:{port}...")

    try:
        while True:
            # 接受客户端连接
            client_socket, addr = server_socket.accept()
            print(f"连接来自 {addr}")
            
            while True:
                # 接收 17 个 double 的数据，总大小为 136 字节
                data = client_socket.recv(136)  # 每个 double 是 8 字节
                if not data:
                    print(f"客户端 {addr} 已断开连接")
                    break  # 退出内层循环，等待下一个客户端

                # 解包接收到的数据
                try:
                    unpacked_data = struct.unpack('>17d', data)
                    get_check1, get_speed, get_mode, get_doit, \
                    get_longitude[0], get_latitude[0], get_altitude[0], \
                    get_longitude[1], get_latitude[1], get_altitude[1], \
                    get_longitude[2], get_latitude[2], get_altitude[2], \
                    get_longitude[3], get_latitude[3], get_altitude[3],get_check2 = unpacked_data

                    print(f"收到来自 {addr} 的数据:")
                    print(f"  经度: {get_longitude}")
                    print(f"  纬度: {get_latitude}")
                    print(f"  高度: {get_altitude}")
                    print(f"  速度: {get_speed}")
                    print(f"  飞行模式: {get_mode}")
                except struct.error as e:
                    print(f"解包数据时发生错误: {e}")



                if get_check1 == 888.0 and get_check2 == 666.0:
                    # 发送确认信息
                    send_check1 = 888.0
                    send_speed = 0.0       # 速度
                    send_mode = 0.0        # 飞行模式/任务：1.0表示...2.0表示...
                    send_doit = 1.0        # 执行确认位(1.0表示有效，0.0表示无效)
                    send_longitude[0] = 0.0   # GPS定位1
                    send_latitude[0] = 0.0
                    send_altitude[0] = 0.0
                    send_longitude[1] = 0.0   # GPS定位2
                    send_latitude[1] = 0.0
                    send_altitude[1] = 0.0
                    send_longitude[2] = 0.0   # GPS定位3
                    send_latitude[2] = 0.0
                    send_altitude[2] = 0.0
                    send_longitude[3] = 0.0   # GPS定位4
                    send_latitude[3] = 0.0
                    send_altitude[3] = 0.0
                    send_check2 = 666.0
                    datas_to_send = [send_check1, send_speed, send_mode,send_doit,\
                                send_longitude[0], send_latitude[0],send_altitude[0],\
                                send_longitude[1], send_latitude[1],send_altitude[1],\
                                send_longitude[2], send_latitude[2],send_altitude[2],\
                                send_longitude[3], send_latitude[3],send_altitude[3],send_check2]
                    try:
                        # 使用 struct 打包数据，16个 double 类型
                        packed_data = struct.pack('>17d', *datas_to_send)
                        # 发送打包的数据到服务器
                        client_socket.sendall(packed_data)
                        print(f"Sent data: {datas_to_send}")
                        send_doit = 0.0     # 确认位清零
                    except BlockingIOError:
                        print("发送数据时阻塞，请稍后再试。")
                    except Exception as e:
                        print(f"发送数据时出错: {e}")
            
            # 关闭当前客户端连接
            client_socket.close()
            print(f"关闭与 {addr} 的连接，准备接收下一个连接...")

    except KeyboardInterrupt:
        print("\n服务器正在关闭...")
    finally:
        server_socket.close()
        print("服务器已关闭。")

if __name__ == "__main__":
    start_server()
